package model

import (
	"encoding/xml"
)

type Device struct {
	Profile Module `xml:"Info"`
	Items   []Item `xml:"Items"`
	//Methods   []DataType.Edge_Method  `xml:"Methods"`
}
type Devices struct {
	XMLName  xml.Name `xml:"AcqConf"`
	Version        string      `xml:"version,attr"`
	Infos []Device `xml:"Device"`
	//Methods   []DataType.Edge_Method  `xml:"Methods"`
}
func(p* Devices)ToXml()([]byte,error){
	return xml.Marshal(p)
}
func(p* Devices)FromXml(data []byte)error{
	return xml.Unmarshal(data,p)
}
func(p* Devices)Save()(err error){
	var er error
	if _,er = DeleteModules();er != nil{
		err = er
	}
	if _,er = DeleteItems();er != nil{
		err = er
	}
	for i:=0; i< len(p.Infos); i++{
		if er = p.Infos[i].Profile.Insert();er != nil{
			err = er
		}
		for j:=0;j < len(p.Infos[i].Items);j++{
			p.Infos[i].Items[j].Id = p.Infos[i].Profile.Id
			//p.Infos[i].Items[j].Tag = p.Infos[i].Profile.Name
			if p.Infos[i].Profile.Catagory == ""{
				p.Infos[i].Items[j].Tag = p.Infos[i].Profile.Name
			}else{
				p.Infos[i].Items[j].Tag =  p.Infos[i].Profile.Catagory + ":"  + p.Infos[i].Profile.Name
			}

		}
		if er = InsertItems(p.Infos[i].Items);er != nil{
			err = er
		}
	}
	if err != nil{
		return
	}else{
		if p.Version == "" {
			p.Version = "V0.00"
		}
		kp :=KeyPair{
			Id:    "device_version",
			Name:  "配置文件版本号",
			Value: p.Version,
		}
		kp.Save()
		return
	}
}
func(p* Devices)Load()error{
	kps :=FindKeyPairs(&KeyPair{Id:"device_version"})
	var version string = "V0.00"
	if kps != nil && len(kps) > 0{
		p.Version = kps[0].Value
	}else{
		p.Version = version
	}
	mods := FindModules(&Module{})
	p.Infos = make([]Device, len(mods))
	for i:=0; i < len(p.Infos); i++{
		p.Infos[i].Profile = mods[i]
		p.Infos[i].Items = FindItems(&Item{Id:mods[i].Id})
	}
	return nil
}